package com.rin.util;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author RinMi
 * @since 2023/6/13
 */
public class ParseEntity {

    private ParseEntity(){}

    public static  <T> T parseEntity(InputStream inputStream, Class<?> clazz) {
        String entityJson = extractEntityJson(inputStream);
        return (T) JSONObject.parseObject(entityJson, clazz);
    }

    private static String extractEntityJson(InputStream inputStream) {
        //将字节流转化为文件流
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        //缓存文件流数据
        StringBuilder stringBuilder = new StringBuilder();
        try {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            return stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                inputStream.close();
                inputStreamReader.close();
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
